package cn.ronghuanet.org.controller;

import cn.ronghuanet.auth.annotation.RonghuaPermission;
import cn.ronghuanet.base.util.AjaxResult;
import cn.ronghuanet.org.domain.Employee;
import cn.ronghuanet.org.service.IEmployeeServiceI;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RonghuaPermission(name = "员工管理api")
@RestController
@RequestMapping("/employee")
@Api(value = "员工管理的api",description = "员工管理的增删改查")
public class EmployeeController {
    @Autowired
    private IEmployeeServiceI service;

    // 查一个通过id

    /**
     * 你要返回数据 你能仅仅返回那个数据
     * 你还要返回 一个 标记符 这样前端更好判断
     *          一个 提示信息 msg
     *          方式一: "{"/"}" 自己拼接
     *          方式二: 使用Map
     *          方式三: 自定义AjaxResult   采用
     *           
     * @param id
     * @return
     */
    // localhost:8080/employee/1
    @RonghuaPermission(name = "查询指定员工")
    @GetMapping("/{id}")
    @ApiOperation(value = "通过id查询员工")
    public AjaxResult selectById(@PathVariable Long id){
        try {
            Employee employee = service.selectById(id);
            return  AjaxResult.success(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

    }
    // 查全部 localhost:8080/employee
    @RonghuaPermission(name = "查询所有员工")
    @GetMapping
    @ApiOperation(value = "查询所有员工")
    public AjaxResult selectAll(){
        try {
            List<Employee> employees = service.selectAll();
            return AjaxResult.success(employees);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
    // 新增/修改
    @RonghuaPermission(name = "新增或修改员工")
    @ApiOperation(value = "新增或修改员工")
    @PostMapping
    public AjaxResult updateOrInsert(@RequestBody Employee employee){
        try {
            if (Objects.nonNull(employee)){
                if (Objects.nonNull(employee.getId())){
                    service.update(employee);
                }else{
                    service.insert(employee);
                }
            }else{
                return AjaxResult.error("请传入正确的参数");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
    // 删除
    @RonghuaPermission(name = "删除指定员工")
    @ApiOperation(value = "通过id删除员工")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@ApiParam(value = "员工id") @PathVariable Long id){
        try {
            service.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


}
